package com.sjzl.dwr;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.sjzl.dao.BaseDao;
import com.sjzl.entity.ProgressInfo;
import com.sjzl.entity.UploadFile;
import com.sjzl.entity.User;
import com.sjzl.util.UploadListener;
import com.sjzl.util.Util;


public class FileUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static final long MAX_LENGTH = 16 * 1024 * 1024L; // 设置上传文件的大小为16MB
	private static final int HTTP_REDUNDANT_LENGTH = 1024; // 1KB

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.getSession().removeAttribute("PROGRESS_INFO");
		RequestDispatcher rd = request.getRequestDispatcher("create_post.jsp");
		rd.forward(request, response);

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Util.info("FileUploadServlet", "posting");

		ProgressInfo pi = new ProgressInfo();
		request.getSession().setAttribute("PROGRESS_INFO", pi);

		try {
			this.doUpload(request, pi);
		} catch (Exception e) {
			pi.setInProgress(false);
			Util.info("FileUploadServlet", "cancelled or interrupted!");
			e.printStackTrace();
			throw new ServletException(e);
		}

		RequestDispatcher rd = request.getRequestDispatcher("create_post.jsp");
		rd.forward(request, response);
	}

	private String getFileName(String fileName) {
		String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
		String realpath = getServletContext().getRealPath("/userUploadFile") ;//获取真实路径
		File file = new File(realpath);
		if(!file.exists()) file.mkdirs();	//如果不存在就创建
		System.out.println();
		return realpath + "/" + name;
	}

	@SuppressWarnings("unchecked")
	private void doUpload(HttpServletRequest request, ProgressInfo pi) throws Exception {
		request.setCharacterEncoding("UTF-8");
		String fldName = "";
		FileItemStream item = null;
		BufferedInputStream stream = null;

		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		List<UploadFile> uploadFiles =new ArrayList<UploadFile>();
		if (isMultipart) {
			int filesSize = request.getContentLength() - HTTP_REDUNDANT_LENGTH;
			if (filesSize >= MAX_LENGTH) {
				String errorMsg = "错误: 当前上传总文件大小为" + filesSize
						/ (1024 * 1024) + "MB 超过了最大的 " + "16MB。";
				pi.setCompleted(true);
				pi.setErrorMsg(errorMsg);
				throw new Exception(errorMsg);
			}
			ServletFileUpload upload = new ServletFileUpload();
			upload.setFileSizeMax(MAX_LENGTH);
			upload.setSizeMax(MAX_LENGTH);
			UploadListener uploadListener = new UploadListener(pi);
			upload.setProgressListener(uploadListener);
			// Parse the request
			FileItemIterator fIter = upload.getItemIterator(request);
			long curTotalLength = 0L;
			while (fIter.hasNext()) {
				item = fIter.next();
				fldName = item.getFieldName();
				System.out.println(fldName);
				Util.info("FileUploadServlet", fldName + ", "+ item.isFormField() + ", " + item.getContentType()+ ", " + item.getName() + ", " + item.getHeaders());

				if (!item.isFormField()) {
					fldName = item.getFieldName();
					if (item.getName() == null || "".equals(item.getName().trim())) {
						continue;
					}
					stream = new BufferedInputStream(item.openStream());

					ByteArrayOutputStream bStream = new ByteArrayOutputStream();

					long bStreamLen = Streams.copy(stream, bStream, true);
				    Util.info("++++++++bStreamLen >> " + bStreamLen);
					curTotalLength = curTotalLength + bStreamLen;

					pi.setCurFileName(item.getName());
					pi.setUploadedFiles(pi.getUploadedFiles() + "<b>"
							+ item.getName() + " (" + bStreamLen / 1024
							+ "KB)</b><br/>");

					Util.info("FileUploadServlet", this.getFileName(item.getName()));	

					String realName = UUID.randomUUID().toString()+ item.getName().substring(item.getName().lastIndexOf("."));// 保存的文件名称，使用UUID+后缀进行保存，可以确保重复上传
					File file = new File(this.getFileName(realName));
//					File file = new File(this.getFileName(item.getName()));
//					if (file.exists()) { //判断文件是否存在，如果存在就把原来的文件删除
//						file.delete(); 
//					}
					//开始往数据库存数据
					UploadFile uploadFile = new UploadFile();
					uploadFile.setDateCreated(new Date());	//保存图片上传时间
					User user = (User)request.getSession().getAttribute("sessionUser");
					uploadFile.setUploadUserAccount(user.getAccount());//保存上传者名称
					uploadFile.setUploadFileType(item.getContentType());	//保存上传文件的类型
					uploadFile.setUploadFileName(item.getName());
					uploadFile.setUploadRealName(realName);
					String realpath = getServletContext().getRealPath("/userUploadFile") ;//获取真实路径
					uploadFile.setServerPath(realpath);
					BaseDao<UploadFile> dao = (BaseDao<UploadFile>)WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()).getBean("daoImpl");
					dao.save(uploadFile);
					
					uploadFiles.add(uploadFile);
					
					OutputStream out = new FileOutputStream(file);
					bStream.writeTo(out);
					Util.info("FileUploadServlet", fldName + " just was uploaded, len " + bStreamLen);
				}

			}
			request.getSession().setAttribute("sessionFileUploads", uploadFiles);
		}

	}

}
